/*
 DNN Content Builder - sourceforge.net/projects/dnncb
 Copyright (c) 2004-2008
 by Emerson Lopes (emersonlopes@gmail.com)

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections;
using System.Data.OleDb;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using DNNContentBuilder.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace DNNContentBuilder.UserControls
{
    /// <summary>
	///		Summary description for ConnectionStringControl.
	/// </summary>
	public class FormBuilderControl : UserControl
	{
		// for localization
		public const string resource = "~/DesktopModules/DNNContentBuilder/App_LocalResources/FormBuilderControl";
		public const string resourceengine = "~/DesktopModules/DNNContentBuilder/App_LocalResources/ResourceEngine";
				
		private ConnectionStringInfo csInfo	= new ConnectionStringInfo();
		private DataConnectionInfo dcInfo	= new DataConnectionInfo();
		private	DatabaseInfo dbInfo			= new DatabaseInfo();

		private int indexField = 0;
		private readonly XmlDocument xmlDoc = new XmlDocument();

		private ArrayList fieldList = new ArrayList();
		private ArrayList dataConnectionList = new ArrayList();
		private ArrayList dataConnectionsSelectedList = new ArrayList();
	
		private bool hasKey = false;
		protected Label msgTestConn;
		protected UserControl Options1;
		protected DataList dlFormList;
		protected LinkButton btNewForm;
		protected Panel FormBuilderFormPanel;
		protected Panel FormBuilderListPanel;
		protected LinkButton btSearchForm;
		protected DropDownList ddConnections;
		protected LinkButton btAdd;
		protected LinkButton btUpdate;
		protected LinkButton btDelete;
		protected LinkButton btCancel;
		protected DataList dlFields;
		protected DataList dlSelectedDataConnections;
		protected HtmlTextArea txtCSS;
		protected TextBox txtFormTitle;
		protected Literal ltLiteral;
		protected ImageButton btMoveUp;
		protected ImageButton btMoveDown;
		protected HtmlInputHidden txtFormId;

		private void Page_Load(object sender, EventArgs e)
		{
			if (IsPostBack) 
			{
				this.btDelete.Attributes.Add("onClick", "javascript:return confirm('" + Commons.GetLocalizedString("label_ConfirmDelete", resource) + "')");
			}

			ltLiteral.Text = "";

			this.btDelete.Text	   = Commons.GetLocalizedString("button_Delete", resource);
			this.btCancel.Text	   = Commons.GetLocalizedString("button_Cancel", resource);
			this.btAdd.Text		   = Commons.GetLocalizedString("button_Add", resource);
			this.btNewForm.Text	   = Commons.GetLocalizedString("button_Create", resource);
			this.btSearchForm.Text = Commons.GetLocalizedString("button_Search", resource);
			this.btUpdate.Text	   = Commons.GetLocalizedString("button_Update", resource);

			if (Session["fieldList"] != null) 
			{
				this.fieldList = (ArrayList)Session["fieldList"];
			} 
			else 
			{
				Session.Add("fieldList", this.fieldList);			
			}
			
			if (Session["dataConnectionList"] != null) 
			{
				this.dataConnectionList = (ArrayList)Session["dataConnectionList"];
			} 
			else 
			{
				Session.Add("dataConnectionList", this.dataConnectionList);
			}

			if (Session["dataConnectionsSelectedList"] != null) 
			{
				this.dataConnectionsSelectedList = (ArrayList)Session["dataConnectionsSelectedList"];
			} 
			else 
			{
				Session.Add("dataConnectionsSelectedList", this.dataConnectionsSelectedList);			
			}

			indexField = 0;

			// Put user code to initialize the page here
			using (FormDefinitionController fdController = new FormDefinitionController())
			{
				this.dlFormList.DataSource = fdController.GetAllFormDefinition();
				this.dlFormList.DataBind();
			}

			int selectedIndex = ddConnections.SelectedIndex;

			using (DataConnectionController dcController = new DataConnectionController())
			{
				this.ddConnections.DataSource = dcController.GetAllDataConnections();
				this.ddConnections.DataTextField = "TableName";
				this.ddConnections.DataValueField = "DataConnectionId";
				this.ddConnections.DataBind();
			}

			ddConnections.SelectedIndex = selectedIndex; 
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.btAdd.Click += new System.EventHandler(this.btAdd_Click);
			this.btNewForm.Click += new System.EventHandler(this.btNewForm_Click);
			this.btDelete.Click += new EventHandler(btDelete_Click);
			this.btCancel.Click += new EventHandler(btCancel_Click);
			this.btUpdate.Click += new EventHandler(btUpdate_Click);
			this.btSearchForm.Click += new EventHandler(btSearchForm_Click);
			this.btMoveDown.Click += new System.Web.UI.ImageClickEventHandler(btMoveDown_Click);
			this.btMoveUp.Click += new System.Web.UI.ImageClickEventHandler(btMoveUp_Click);

			this.Load += new System.EventHandler(this.Page_Load);
			this.dlSelectedDataConnections.ItemCreated += new DataListItemEventHandler(dlSelectedDataConnections_ItemCreated);
			this.dlFormList.ItemCreated += new DataListItemEventHandler(dlFormList_ItemCreated);
			this.dlFields.ItemCreated += new DataListItemEventHandler(dlFields_ItemCreated);
			this.dlFields.ItemDataBound += new DataListItemEventHandler(dlFields_ItemDataBound);

			((DNNContentBuilder.UserControls.FieldControls.FieldType)Options1).RebuildFieldListEvent += new EventHandler(dlFields_UpdateDataList);
			
		}
		#endregion

		private void dlFields_UpdateDataList(object sender, EventArgs e) {
			if (Session["lastButton"] == null) {
				throw new Exception("ERROR:lastButton?");
			}
			
			if (Session["fieldList"] == null) {
				throw new Exception("ERROR:fieldList?");
			}

			try 
			{
				fieldList = (ArrayList)Session["fieldList"];
			}
			catch (Exception err) 
			{
				throw new Exception(((ArrayList)Session["fieldList"]).GetType().ToString()+err.Message);
			}
				
			ArrayList titleFields = SaveSelectedFields();

			dlFields.DataSource = fieldList;
			dlFields.DataBind();

			ShowSelectedButton();

			RestoreSelectedFields(titleFields);
		}
		
		private void dlFormList_ItemCreated(object sender, DataListItemEventArgs e) 
		{ 
			ListItemType elemType = e.Item.ItemType;

			if ((elemType == ListItemType.Item) || (elemType == ListItemType.AlternatingItem))
			{ 
				Control btFormSelected = e.Item.FindControl("btFormSelected"); 

				ArgumentValidator.CheckForNullReference(btFormSelected, "btFormSelected");
				ArgumentValidator.CheckForExpectedType(btFormSelected, "btFormSelected", typeof(ImageButton));

				ImageButton imageButton = btFormSelected as ImageButton;
			    if (imageButton != null) imageButton.Click += btFormSelected_OnClick;
			}  
		}

		private void btFormSelected_OnClick(object sender, ImageClickEventArgs e)
		{
			ImageButton btFormSelected = (ImageButton)sender;

			FormDefinitionInfo fdInfo = new FormDefinitionInfo();

			using (FormDefinitionController fdController = new FormDefinitionController())
			{
				fdInfo = fdController.GetItem(Int32.Parse(btFormSelected.CommandArgument));
			}

			FormDataConnectionsController fdcController = new FormDataConnectionsController();

			ArrayList fdcList = new ArrayList();

			fdcList = fdcController.GetByFormDefinition(fdInfo.FormDefinitionId);

			using (DataConnectionController dcController = new DataConnectionController())
			{
				for (int indexForm = 0;indexForm < fdcList.Count;indexForm++) 
				{
					DataConnectionInfo dcTemp = dcController.GetItem(((FormDataConnectionsInfo)fdcList[indexForm]).DataConnectionId);

					this.dataConnectionList.Add(dcTemp);
				}
			}

			FieldDefinitionController fieldController = new FieldDefinitionController();

			fdcList = fieldController.GetFieldDefinitionControlTypes(fdInfo.FormDefinitionId);

			XmlDocument tempXml = new XmlDocument();

			XmlNode tempNode;

			tempXml.Load(HttpContext.Current.Server.MapPath("~\\DesktopModules\\DNNContentBuilder\\UserControls\\FieldControls\\XML\\RegularProperties.xml"));

			ControlTypeInfo ctInfo = new ControlTypeInfo();

			using (ControlTypeController ctController = new ControlTypeController())
			using (DataConnectionController dcController = new DataConnectionController())
			{
				for (int indexXml=0; indexXml < fdcList.Count; indexXml++) 
				{
					FieldDefinitionInfo field = (FieldDefinitionInfo)fdcList[indexXml];
					tempNode = tempXml.SelectSingleNode("//SourceField");

					tempNode.InnerText = field.SourceField;

					string table = tempNode.InnerText.Split('.')[0];

					ctInfo = ctController.GetItem(field.ControlTypeId);

					tempNode = tempXml.SelectSingleNode("//ControlPath");
					tempNode.InnerText = ctInfo.ControlPath;

					tempNode = tempXml.SelectSingleNode("//DataConnectionId");

					dcInfo = dcController.GetItemByTableName(table); 

					tempNode.InnerText = dcInfo.DataConnectionId.ToString();

					tempNode = tempXml.SelectSingleNode("//FriendlyName");
					tempNode.InnerText = field.Title;

					tempNode = tempXml.SelectSingleNode("//CssClass");
					tempNode.InnerText = field.CssClass;

					tempNode = tempXml.SelectSingleNode("//Search");
					tempNode.InnerText = field.Search.ToString();

					tempNode = tempXml.SelectSingleNode("//Tooltip");
					tempNode.InnerText = field.Tooltip;

					tempNode = tempXml.SelectSingleNode("//Required");
					tempNode.InnerText = field.Required.ToString();

					tempNode = tempXml.SelectSingleNode("//Visible");
					tempNode.InnerText = field.Visible.ToString();

					tempNode = tempXml.SelectSingleNode("//IsTitle");
					tempNode.InnerText = field.IsTitle.ToString();

					tempNode = tempXml.SelectSingleNode("//ExtendedProperties");
					tempNode.InnerXml = field.XML;
					
					string controlTypeName = tempNode.FirstChild.Name;
					
					fieldList.Add(new FieldInfo(field.Title, tempXml.InnerXml, field.SourceField, field.ControlTypeId, dcInfo.DataConnectionId, controlTypeName));
				}
			}

			this.txtFormTitle.Text = fdInfo.Title;
			this.txtCSS.Value = fdInfo.CSS;
			this.txtFormId.Value = fdInfo.FormDefinitionId.ToString();
			
			this.dlSelectedDataConnections.DataSource = this.dataConnectionList;
			this.dlSelectedDataConnections.DataBind();

			this.dlFields.DataSource = fieldList;
			this.dlFields.DataBind();

			DisplayTitleFields(fieldList);

			Session.Add("fieldList", this.fieldList);			
			Session.Add("dataConnectionList", this.dataConnectionList);			
			Session.Add("dataConnectionsSelectedList", this.dataConnectionsSelectedList);			

			FormBuilderListPanel.Visible=false;
			FormBuilderListPanel.Enabled=false;

			FormBuilderFormPanel.Visible=true;
			FormBuilderFormPanel.Enabled=true;

			this.btDelete.Visible = true;
		}

		private void RemoveSessions() 
		{
			Session.Remove("fieldList");
			Session.Remove("dataConnectionsSelectedList");
			Session.Remove("dataConnectionList");
			Session.Remove("myHeader");
			Session.Remove("myControl");
			Session.Remove("myFooter");
			Session.Remove("lastButton");
		}

		private void btSearchForm_Click(object sender, EventArgs e)
		{
			RemoveSessions();
			ResetPanels();
		}

		private void ResetPanels()
		{
			Options1.Visible = false;

			FormBuilderListPanel.Visible=true;
			FormBuilderListPanel.Enabled=true;

			FormBuilderFormPanel.Visible=false;
			FormBuilderFormPanel.Enabled=false;

			this.btDelete.Visible=false;
		}

		private void ClearFields()
		{
			RemoveSessions();
			ResetPanels();

			Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(), true);
		}

		private void btNewForm_Click(object sender, EventArgs e)
		{
			RemoveSessions();

			this.txtFormTitle.Text = "";
			this.txtFormId.Value = "";

			this.dlSelectedDataConnections.DataSource = null;
			this.dlSelectedDataConnections.DataBind();

			this.dlFields.DataSource = null;
			this.dlFields.DataBind();

			FormBuilderListPanel.Visible=false;
			FormBuilderListPanel.Enabled=false;

			FormBuilderFormPanel.Visible=true;
			FormBuilderFormPanel.Enabled=true;

			using (StreamReader file = new StreamReader(HttpContext.Current.Server.MapPath("~\\DesktopModules\\DNNContentBuilder\\template.css"))) 
			{
				txtCSS.Value = file.ReadToEnd();
			}
		}

		private void btAdd_Click(object sender, EventArgs e)
		{
			if (this.ddConnections.Items.Count == 0) 
			{
				return;
			}

			DataConnectionInfo dcInfoTemp;

			for (int index = 0;index < this.dataConnectionList.Count;index++) 
			{
				dcInfoTemp = (DataConnectionInfo)dataConnectionList[index];

				if (dcInfoTemp.DataConnectionId == Int32.Parse(this.ddConnections.SelectedValue)) 
				{
					return;
				}
			}
			
			string primaryKeyField = "";
					
			using (ConnectionProvider cp = new ConnectionProvider())
			using (DataConnectionController dcController = new DataConnectionController(cp))
			using (ConnectionStringController csController = new ConnectionStringController(cp))
			using (DatabaseController dbController = new DatabaseController(cp))
			{
				cp.BeginTransaction();

				dcInfoTemp = dcController.GetItem(Int32.Parse(this.ddConnections.SelectedValue));

				this.dataConnectionList.Add(dcInfoTemp);
				
				primaryKeyField = dcInfoTemp.PrimaryKeyName;

				// adding fields

				csInfo = csController.GetItem(dcInfoTemp.ConnectionStringId);
				dbInfo = dbController.GetItem(csInfo.DatabaseId);
			}

			string cmdText = (dbInfo.SysColumnQuery.Replace("@table_name", this.ddConnections.SelectedItem.Text)).Replace("order by sc.name", "");
			
			bool hasElements = false;
			
			if (Session["fieldlist"] != null) {
				if (((ArrayList)Session["fieldlist"]).Count > 0) {
					hasElements = true;
				}
			}

			using (OleDbConnection conn = new OleDbConnection(csInfo.ConnectionString))
			using (OleDbCommand command = new OleDbCommand(cmdText, conn))
			{
				try 
				{
					conn.Open();
					
					using (OleDbDataReader reader = command.ExecuteReader())
					{
						while (reader.Read()) 
						{
							string name = reader.GetString(0);
							fieldList.Add(new FieldInfo(name, "", name, 0, dcInfoTemp.DataConnectionId, ""));
						}
					}
					
					// if list is empty, then first field must be the PK
					if (!hasElements) {
						ArrayList reOrderedList = new ArrayList();
					
						object pk = new object();
					
						foreach (FieldInfo fi in fieldList) {
							if (fi.name == primaryKeyField) {
								pk = fi;
							} else {
								reOrderedList.Add(fi);
							}
						}
						
						fieldList.Clear();
					
						fieldList.Add((FieldInfo)pk);
					
						foreach (FieldInfo fi in reOrderedList) {
							fieldList.Add(fi);
						}
					}

					ArrayList selectedTitles = SaveSelectedFields();

					this.dlFields.DataSource = fieldList;
					this.dlFields.DataBind();

					RestoreSelectedFields(selectedTitles);
				}
				catch (Exception ) 
				{
					return;
				}
			}

			this.dlSelectedDataConnections.DataSource = this.dataConnectionList;
			this.dlSelectedDataConnections.DataBind();

			Session.Add("fieldList", this.fieldList);			
			Session.Add("dataConnectionList", this.dataConnectionList);			
			Session.Add("dataConnectionsSelectedList", this.dataConnectionsSelectedList);			
		}

		private void SyncTitleFields()
		{
			foreach (DataListItem item in dlFields.Items)
			{
				Control rbTitle = item.FindControl("rbTitle");

				ArgumentValidator.CheckForNullReference(rbTitle, "rbTitle");
				ArgumentValidator.CheckForExpectedType(rbTitle, "rbTitle", typeof(RadioButtonEx));

				RadioButtonEx radio = rbTitle as RadioButtonEx;

				foreach (FieldInfo fieldDefinition in this.fieldList)
				{
					ArgumentValidator.CheckForNullReference(fieldDefinition.columnProperties, "fieldDefinition.columnProperties");

					string xml = fieldDefinition.columnProperties;

					if (xml.Length == 0)
					{
						// Column properties has been emptied. Reload from regularproperties.xml
						string path = HttpContext.Current.Server.MapPath("~\\DesktopModules\\DNNContentBuilder\\UserControls\\FieldControls\\XML\\RegularProperties.xml");

						using (StreamReader reader = new StreamReader(path))
						{
							xml = reader.ReadToEnd();

							XmlDocument reloadedXml = new XmlDocument();
							reloadedXml.LoadXml(xml);

							XmlNode myNode = reloadedXml.SelectSingleNode("//SourceField");
							myNode.InnerText = fieldDefinition.columnType;

							xml = reloadedXml.InnerXml;
						}
					}

					XmlDocument xdoc = new XmlDocument();
					xdoc.LoadXml(xml);

					XmlNode titleNode = xdoc.SelectSingleNode("//IsTitle");
					XmlNode fieldNode = xdoc.SelectSingleNode("//SourceField");

					ArgumentValidator.CheckForNullReference(titleNode, "titleNode");
					ArgumentValidator.CheckForNullReference(fieldNode, "fieldNode");
					ArgumentValidator.CheckForEmptyString(fieldNode.InnerText, "fieldNode.InnerText");

				    if (radio != null)
				        if (fieldNode.InnerText == radio.RadioValue)
				        {
				            titleNode.InnerText = radio.Checked.ToString();
				            fieldDefinition.columnProperties = xdoc.InnerXml;
				        }
				}

				Control btFormField = item.FindControl("btFormField");

				ArgumentValidator.CheckForNullReference(btFormField, "btFormField");
				ArgumentValidator.CheckForExpectedType(btFormField, "btFormField", typeof(ImageButton));

				ImageButton imgAvailableField = btFormField as ImageButton;
				
				foreach (FieldInfo fieldDefinition in fieldList) 
				{
				    if (imgAvailableField != null)
				        if (fieldDefinition.name == imgAvailableField.CommandName) 
				        {
				            imgAvailableField.CommandArgument = fieldDefinition.columnProperties;
				            break;
				        }
				}
			}

			Session["fieldList"] = fieldList;
		}

      private void DisplayTitleFields(ArrayList fieldList)
		{
		    if (fieldList == null) throw new ArgumentNullException("fieldList");
		    foreach (FieldInfo fieldDefinition in fieldList)
			{
				string xml = fieldDefinition.columnProperties;
				
				XmlDocument xdoc = new XmlDocument();
				xdoc.LoadXml(xml);

				XmlNode titleNode = xdoc.SelectSingleNode("//IsTitle");
				XmlNode fieldNode = xdoc.SelectSingleNode("//SourceField");

				ArgumentValidator.CheckForNullReference(titleNode, "titleNode");
				ArgumentValidator.CheckForNullReference(fieldNode, "fieldNode");
				ArgumentValidator.CheckForEmptyString(fieldNode.InnerText, "fieldNode.InnerText");

				if (titleNode.InnerText.Length > 0)
				{
					bool isTitle = Boolean.Parse(titleNode.InnerText);

					foreach (DataListItem item in dlFields.Items)
					{
						Control rbTitle = item.FindControl("rbTitle");

						ArgumentValidator.CheckForNullReference(rbTitle, "rbTitle");
						ArgumentValidator.CheckForExpectedType(rbTitle, "rbTitle", typeof(RadioButtonEx));

						RadioButtonEx radio = rbTitle as RadioButtonEx;

					    if (radio != null)
					        if (radio.RadioValue == fieldNode.InnerText)
					        {
					            radio.Checked = isTitle;
					        }
					}
				}
			}
		}

        private void dlSelectedDataConnections_ItemCreated(object sender, DataListItemEventArgs e) 
		{ 
			ListItemType elemType = e.Item.ItemType;

			if (elemType == ListItemType.Item || elemType == ListItemType.AlternatingItem)
			{ 
				Control btDelDataConnection = e.Item.FindControl("btDelDataConnection"); 

				ArgumentValidator.CheckForNullReference(btDelDataConnection, "btDelDataConnection");
				ArgumentValidator.CheckForExpectedType(btDelDataConnection, "btDelDataConnection", typeof(ImageButton));

				ImageButton imageButton = btDelDataConnection as ImageButton;

			    if (imageButton != null)
			        imageButton.Click += btDelDataConnection_OnClick;
			}
		}

		private void btFormField_OnClick(object sender, ImageClickEventArgs e)
		{
			Session.Remove("myHeader");
			Session.Remove("myControl");
			Session.Remove("myFooter");

			this.Options1.Visible = false;

			SyncTitleFields();

			if (Session["lastButton"] != null)
			{
				try 
				{
					Control lastButton = Page.FindControl((string)Session["lastButton"]);

					ArgumentValidator.CheckForNullReference(lastButton, "lastButton");
					ArgumentValidator.CheckForExpectedType(lastButton, "lastButton", typeof(ImageButton));

					ImageButton imgLastButton = lastButton as ImageButton;

				    if (imgLastButton != null) imgLastButton.ImageUrl = "~/DesktopModules/DNNContentBuilder/images/action.gif";

				    XmlDocument tempXml = new XmlDocument();

				    if (imgLastButton != null) tempXml.LoadXml(imgLastButton.CommandArgument);

				    XmlNode tempNode = tempXml.SelectSingleNode("//ExtendedProperties");

					if (tempNode != null) 
					{
						if (tempNode.InnerText != "") 
						{
						    if (imgLastButton != null)
						        imgLastButton.ImageUrl = "~/DesktopModules/DNNContentBuilder/images/actionDone.gif";

						    XmlNode xmlNode = tempXml.SelectSingleNode("//Linker");
						
							if (xmlNode != null) 
							{
							    if (imgLastButton != null) imgLastButton.ImageUrl = "~/DesktopModules/DNNContentBuilder/images/linker.gif";
							}
						}

						if (tempNode.InnerText == "GUID") 
						{ 
							if (!hasKey)
							{
							    if (imgLastButton != null) imgLastButton.ImageUrl = "~/DesktopModules/DNNContentBuilder/images/key.gif";
							    hasKey = true;
							}
							else 
							{
							    if (imgLastButton != null)
							        imgLastButton.ImageUrl = "~/DesktopModules/DNNContentBuilder/images/keyLinker.gif";
							}
						}
					}

					ArrayList myList = (ArrayList)Session["fieldList"];

					foreach (FieldInfo field in myList) 
					{
					    if (imgLastButton != null)
					        if (field.name == imgLastButton.CommandName) 
					        {
					            imgLastButton.CommandArgument = field.columnProperties;
					            break;
					        }
					}
				}
				catch 
				{
					// TODO: either handle or catch a more specific exception class
				}
			}

			Session.Add("lastButton", ((ImageButton)sender).UniqueID);	
		
			((ImageButton)sender).ImageUrl = "~/DesktopModules/DNNContentBuilder/images/properties.gif";

			// Some how, and I have no time to investigate it, sometimes CommandArgument is empty, 
			// so the code below fix it
			XmlDocument reloadedXml = new XmlDocument();

			XmlNode node;

			if (((ImageButton)sender).CommandArgument == "") 
			{
				reloadedXml.Load(HttpContext.Current.Server.MapPath("~\\DesktopModules\\DNNContentBuilder\\UserControls\\FieldControls\\XML\\RegularProperties.xml"));

				node = reloadedXml.SelectSingleNode("//SourceField");
				node.InnerText = ((ImageButton)sender).CommandName;

				((ImageButton)sender).CommandArgument = reloadedXml.OuterXml;
			}

			reloadedXml.LoadXml(((ImageButton)sender).CommandArgument);
			
			node = reloadedXml.SelectSingleNode("//ControlPath");

			if (node != null) 
			{
				if (node.InnerText != "") 
				{
					FieldControls.FieldType fieldType = (FieldControls.FieldType)Options1;
					fieldType.SetSelected(node.InnerText);
				}
			}

			this.Options1.Visible = true;
			
			HideFieldSettingsPane();
		}

		private void HideFieldSettingsPane()
		{
			Control pnDynamicControl = Options1.FindControl("pnDynamicControl");
			
			ArgumentValidator.CheckForNullReference(pnDynamicControl, "pnDynamicControl");

			pnDynamicControl.Visible = false;

			Control btUpdateProperties = Options1.FindControl("btUpdateProperties");
			
			ArgumentValidator.CheckForNullReference(btUpdateProperties, "btUpdateProperties");

			btUpdateProperties.Visible = false;
		}

		private void btDelDataConnection_OnClick(object sender, ImageClickEventArgs e)
		{
			ArgumentValidator.CheckForNullReference(sender, "sender");
			ArgumentValidator.CheckForExpectedType(sender, "sender", typeof(ImageButton));

			ImageButton btDataConnSelected = (ImageButton)sender;

			using (DataConnectionController dcController = new DataConnectionController())
			{
				dcInfo = dcController.GetItem(Int32.Parse(btDataConnSelected.CommandArgument));
			}

			// delete fields
			int index = fieldList.Count - 1;

			for (;index > -1;index--) 
			{
				if (((FieldInfo)fieldList[index]).DataConnectionId == dcInfo.DataConnectionId) 
				{
					fieldList.RemoveAt(index);
				}
			}

			index = dataConnectionList.Count - 1;

			for (;index > -1;index--) 
			{
				if (((DataConnectionInfo)dataConnectionList[index]).DataConnectionId == dcInfo.DataConnectionId) 
				{
					dataConnectionList.RemoveAt(index);
				}
			}

			this.dlSelectedDataConnections.DataSource = this.dataConnectionList;
			this.dlSelectedDataConnections.DataBind();

			Session.Add("dataConnectionList", this.dataConnectionList);			

			ArrayList selectedTitles = SaveSelectedFields();

			this.dlFields.DataSource = fieldList;
			this.dlFields.DataBind();

			RestoreSelectedFields(selectedTitles);
			HideFieldSettingsPane();

			Session.Add("fieldList", fieldList);
		}

		private void btMoveUp_Click(object sender, ImageClickEventArgs e)
		{
			Options1.Visible = false;

			if (Session["lastButton"] == null) 
			{
				ltLiteral.Text = Commons.GetLocalizedString("message_SelectField", resource);

				return;
			}
			
			if (Session["fieldList"] != null) 
			{
				FieldInfo tempField;

				fieldList = (ArrayList)Session["fieldList"];

				if (fieldList.Count < 2) 
				{
					return;
				}

				Control lastButton = Page.FindControl((string)Session["lastButton"]);

				if (lastButton == null) 
				{
					return;
				}

				tempField = (FieldInfo)fieldList[0];

				int loop = 0;

				for (;loop < fieldList.Count;loop++) 
				{
					tempField = (FieldInfo)fieldList[loop];

					if (tempField.name == ((ImageButton)lastButton).CommandName) 
					{
						break;
					}
				}
				
				// do nothing if there is only one field in the form
				if (loop == 0) 
				{
					return;
				}

				fieldList[loop] = fieldList[loop - 1];
				fieldList[loop - 1] = tempField;

				ArrayList titleFields = SaveSelectedFields();

				this.dlFields.DataSource = fieldList;
				this.dlFields.DataBind();

				RestoreSelectedFields(titleFields);

				Session.Add("fieldList", fieldList);
				
				ShowSelectedButton(tempField);
			}
		}

		private void ShowSelectedButton() {
			Control lastButton = Page.FindControl((string)Session["lastButton"]);
			
			((ImageButton)lastButton).ImageUrl = "~/DesktopModules/DNNContentBuilder/images/properties.gif";
		}
		
		private void ShowSelectedButton(FieldInfo tempField) {
			foreach(DataListItem item in dlFields.Items) {
				foreach (Control control in item.Controls) {
					if (control is ImageButton) {
						if (((ImageButton)control).CommandName == tempField.name) {
							Session["lastButton"] = ((ImageButton)control).UniqueID;
							break;
						}
					}
				}
			}
			
			Control lastButton = Page.FindControl((string)Session["lastButton"]);
			
			((ImageButton)lastButton).ImageUrl = "~/DesktopModules/DNNContentBuilder/images/properties.gif";
		}

		private ArrayList SaveSelectedFields()
		{
			ArrayList result = new ArrayList();

			foreach (DataListItem item in dlFields.Items)
			{
				Control rbTitle = item.FindControl("rbTitle") as Control;
				
				ArgumentValidator.CheckForNullReference(rbTitle, "rbTitle");
				ArgumentValidator.CheckForExpectedType(rbTitle, "rbTitle", typeof(RadioButtonEx));

				RadioButtonEx radio = (RadioButtonEx)rbTitle;

				if (radio.Checked)
				{
					result.Add(radio.RadioValue);
				}
			}

			return result;
		}

		private void RestoreSelectedFields(IList selectedFields)
		{
			foreach (DataListItem item in dlFields.Items)
			{
				Control rbTitle = item.FindControl("rbTitle") as Control;
				
				ArgumentValidator.CheckForNullReference(rbTitle, "rbTitle");
				ArgumentValidator.CheckForExpectedType(rbTitle, "rbTitle", typeof(RadioButtonEx));

				RadioButtonEx radio = (RadioButtonEx)rbTitle;

				if (selectedFields.Contains(radio.RadioValue))
				{
					radio.Checked = true;
				}
			}
		}

		private void btMoveDown_Click(object sender, ImageClickEventArgs e)
		{
			Options1.Visible = false;

			if (Session["lastButton"] == null) 
			{
				ltLiteral.Text = Commons.GetLocalizedString("message_SelectField", resource);

				return;
			}
			
			ltLiteral.Text = "";

			if (Session["fieldList"] != null) 
			{
				FieldInfo tempField;

				fieldList = (ArrayList)Session["fieldList"];

				if (fieldList.Count < 2) 
				{
					return;
				}

				Control lastButton = Page.FindControl((string)Session["lastButton"]);

				if (lastButton == null) 
				{
					return;
				}

				tempField = (FieldInfo)fieldList[0];

				int loop = 0;

				for (;loop < fieldList.Count;loop++) 
				{
					tempField = (FieldInfo)fieldList[loop];

					if (tempField.name == ((ImageButton)lastButton).CommandName) 
					{
						break;
					}
				}

				//do nothing if selected field is the last field on the list
				if (loop == (fieldList.Count - 1)) 
				{
					return;
				}

				fieldList[loop] = fieldList[loop + 1];
				fieldList[loop + 1] = tempField;

				ArrayList titleFields = SaveSelectedFields();
				
				this.dlFields.DataSource = fieldList;
				this.dlFields.DataBind();

				RestoreSelectedFields(titleFields);

				Session.Add("fieldList", fieldList);
				
				ShowSelectedButton(tempField);
			}
		}

		private void btUpdate_Click(object sender, EventArgs e)
		{
			if (this.txtFormTitle.Text == "") 
			{
				return;
			}

			ArrayList myList = (ArrayList)Session["fieldList"];

			FormDefinitionInfo fdInfo = new FormDefinitionInfo();

			fdInfo.Title = this.txtFormTitle.Text;
			fdInfo.CSS = this.txtCSS.Value;

		    using (ConnectionProvider cp = new ConnectionProvider())
			using (ControlTypeController ctController = new ControlTypeController(cp))
			using (DataConnectionController dcController = new DataConnectionController(cp))
			using (FieldDefinitionController fieldController = new FieldDefinitionController(cp))
			using (FormDataConnectionsController fdcController = new FormDataConnectionsController(cp))
			using (FormDefinitionController fdController = new FormDefinitionController(cp))
			{
				cp.BeginTransaction();

				if (txtFormId.Value == "") 
				{
					fdInfo.FormDefinitionId = fdController.Add(fdInfo);
				} 
				else 
				{
					fdInfo.FormDefinitionId = Int32.Parse(txtFormId.Value);
					fdController.Update(fdInfo);
				}

				int formId = fdInfo.FormDefinitionId;

				FieldDefinitionInfo fieldInfo = new FieldDefinitionInfo();

				fieldController.DeleteAllFieldDefinitions(fdInfo.FormDefinitionId);

				XmlNode xmlNode;
				bool found = false;

				ControlTypeInfo ctInfo = new ControlTypeInfo();

				indexField = 0;

				int titles = 0;

				for (;indexField < myList.Count;indexField++) 
				{
					FieldInfo field = (FieldInfo)myList[indexField];

					if (field.columnProperties != "") 
					{
						xmlDoc.LoadXml(field.columnProperties);	

						xmlNode = xmlDoc.SelectSingleNode("//SourceField");

						#region SourceField property
						if (xmlNode.InnerText != "") 
						{
							fieldInfo.SourceField = xmlNode.InnerText;

							xmlNode = xmlDoc.SelectSingleNode("//FriendlyName");

							#region FriendlyName property
							if (xmlNode.InnerText != "") 
							{
								fieldInfo.Title = xmlNode.InnerText;

								xmlNode = xmlDoc.SelectSingleNode("//CssClass");

								fieldInfo.CssClass = xmlNode.InnerText;

								xmlNode = xmlDoc.SelectSingleNode("//Tooltip");

								fieldInfo.Tooltip = xmlNode.InnerText;

								xmlNode = xmlDoc.SelectSingleNode("//Search");

								#region Search property
								if (xmlNode.InnerText != "") 
								{
									if (xmlNode.InnerText.ToLower() == "true")
									{
										fieldInfo.Search = true;
									} 
									else 
									{
										fieldInfo.Search = false;
									}

									xmlNode = xmlDoc.SelectSingleNode("//Required");

									#region Required property

									if (xmlNode.InnerText != "") 
									{
										if (xmlNode.InnerText.ToLower() == "true") 
										{
											fieldInfo.Required = true;
										} 
										else 
										{
											fieldInfo.Required = false;
										}
										xmlNode = xmlDoc.SelectSingleNode("//ExtendedProperties");

										#region ExtendedProperties
										if (xmlNode.InnerXml != "") 
										{
											fieldInfo.XML = xmlNode.InnerXml;
											fieldInfo.ControlTypeId = ctInfo.ControlTypeId;;
											fieldInfo.FormDefinitionId = formId;
											fieldInfo.TabIndex = indexField;

											#region Visible
											xmlNode = xmlDoc.SelectSingleNode("//Visible");

											if (xmlNode.InnerText.ToLower() == "true") 
											{
												fieldInfo.Visible = true;
											} 
											else 
											{
												fieldInfo.Visible = false;
											}
											#endregion

											#region IsTitle
											xmlNode = xmlDoc.SelectSingleNode("//IsTitle");

											if (xmlNode.InnerText.ToLower() == "true") 
											{
												fieldInfo.IsTitle = true;
												titles++;
											} 
											else 
											{
												fieldInfo.IsTitle = false;
											}
											#endregion

											xmlNode = xmlDoc.SelectSingleNode("//ControlPath");

											ctInfo = ctController.GetItemByPath(xmlNode.InnerText);
											fieldInfo.ControlTypeId = ctInfo.ControlTypeId;

											dcInfo = dcController.GetItemByTableName(fieldInfo.SourceField.Split('.')[0]);

											fieldInfo.DataConnectionId = dcInfo.DataConnectionId;
											fieldController.Add(fieldInfo);

											found = true;
										}
										#endregion
									} 
									#endregion
								}
								#endregion
							}
							#endregion
						}
						#endregion

					}//end if
				}//end foreach

				if (!found || titles != this.dlSelectedDataConnections.Items.Count) 
				{
					cp.Rollback();
					return;
				} 
				else 
				{
					FormDataConnectionsInfo fdcInfo = new FormDataConnectionsInfo();

					fdcController.DeleteByFormDefinition(formId);

					for (int index = 0;index < dataConnectionList.Count;index++)
					{
						fdcInfo.DataConnectionId = ((DataConnectionInfo)dataConnectionList[index]).DataConnectionId;
						fdcInfo.FormDefinitionId = formId;

						fdcController.Add(fdcInfo);
					}
					
					cp.Commit();
				}
			}

			this.ClearFields();
		}

		private void btCancel_Click(object sender, EventArgs e)
		{
			this.ClearFields();
		}

		private void btDelete_Click(object sender, EventArgs e)
		{
			Int32 formId = Int32.Parse(this.txtFormId.Value);

			using (ConnectionProvider cp = new ConnectionProvider())
			using (FieldDefinitionController fieldController = new FieldDefinitionController(cp))
			using (FormDataConnectionsController fdcController = new FormDataConnectionsController(cp))
			using (FormDefinitionController fdController = new FormDefinitionController(cp))
			using (new ContentManagerSettingsController(cp))
			{
			    cp.BeginTransaction();

			    fieldController.DeleteAllFieldDefinitions(formId);
			    fdcController.DeleteByFormDefinition(formId);
				
			    try
			    {
			        fdController.Delete(formId);
			    }
			    catch (System.Data.SqlClient.SqlException ex)
			    {
			        const string mdConstraintName  = "FK_epMetaData_epFormDefinition";
			        const string cmsConstraintName = "FK_epContentManagerSettings_epFormDefinition";

			        if (ex.Message.IndexOf(cmsConstraintName) != -1)
			        {
			            // TODO: provide a means to delete content manager settings (de-associate a form definition with a module)
			            throw new ApplicationException(Commons.GetLocalizedString("ERR_FORM_DEFINITION_IN_USE", resourceengine));
			        }

			        if (ex.Message.IndexOf(mdConstraintName) != -1)
			        {
			            throw new ApplicationException(Commons.GetLocalizedString("ERR_FORM_DEFINITION_METADATA", resourceengine));
			        }
					
			        throw;
			    }
				
			    cp.Commit();
			}

			this.ClearFields();
		}

		private void dlFields_ItemDataBound(object sender, DataListItemEventArgs e)
		{
			if (Session["fieldList"] == null) 
			{
				return;
			}

			ListItemType elemType = e.Item.ItemType;

			FieldInfo tempField;

			if ((elemType == ListItemType.Item) || (elemType == ListItemType.AlternatingItem))
			{ 
				ImageButton btFormField = (ImageButton) e.Item.FindControl("btFormField");

				//load "template" XML
				XmlDocument tempXml = new XmlDocument();

				XmlNode tempNode;

				fieldList = (ArrayList)Session["fieldList"];
				
				tempField = (FieldInfo)fieldList[indexField];
				
				indexField++;
				
				if (tempField.columnProperties != "") 
				{
					tempXml.LoadXml(tempField.columnProperties);
				} 
				else 
				{
					tempXml.Load(HttpContext.Current.Server.MapPath("~\\DesktopModules\\DNNContentBuilder\\UserControls\\FieldControls\\XML\\RegularProperties.xml"));
					tempNode = tempXml.SelectSingleNode("//SourceField");
					tempNode.InnerText = btFormField.CommandName;
				}

				btFormField.CommandArgument = tempXml.OuterXml;

				tempNode = tempXml.SelectSingleNode("//ExtendedProperties");

     			if (tempNode.InnerText == "") 
				{ 
					btFormField.ImageUrl = "~/DesktopModules/DNNContentBuilder/images/action.gif";
				}

				if (tempNode.InnerText != "") 
				{ 
					btFormField.ImageUrl = "~/DesktopModules/DNNContentBuilder/images/actionDone.gif";
					XmlNode xmlNode = tempXml.SelectSingleNode("//Linker");
					
					if (xmlNode != null) 
					{
						btFormField.ImageUrl = "~/DesktopModules/DNNContentBuilder/images/linker.gif";
					}
				}

				if (tempNode.InnerText == "GUID") 
				{ 
					if (!hasKey) 
					{
						btFormField.ImageUrl = "~/DesktopModules/DNNContentBuilder/images/key.gif";
						hasKey = true;
					} 
					else 
					{
						btFormField.ImageUrl = "~/DesktopModules/DNNContentBuilder/images/keyLinker.gif";
					}
				}
			}
		}

		private void dlFields_ItemCreated(object sender, DataListItemEventArgs e)
		{
			// This is not fair
			if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
			{
				Control btFormField = e.Item.FindControl("btFormField");

				ArgumentValidator.CheckForNullReference(btFormField, "btFormField");
				ArgumentValidator.CheckForExpectedType(btFormField, "btFormField", typeof(ImageButton));

				ImageButton imageButton = btFormField as ImageButton;

			    if (imageButton != null) imageButton.Click += btFormField_OnClick;
			}
		}
	}
}
